package token

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

type jwtCustomClaims struct {
	jwt.StandardClaims

	// 追加自己需要的信息
	Uid      int   `json:"uid"`
	Username string `json:"username"`
	Password string `json:"password"`
	Secret   string `json:"secret"`
}

/**
 * 生成 token
 * SecretKey 是一个 const 常量
 */
func CreateToken(SecretKey string, issuer string, Uid int, name, pass string) (tokenString string, err error) {
	claims := &jwtCustomClaims{
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
			Issuer:    issuer,
		},
		Uid,
		name,
		pass,
		SecretKey,
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err = token.SignedString([]byte(SecretKey))
	return
}

/**
 * 解析 token
 */
func ParseToken(tokenSrt string, SecretKey string) (claims jwt.Claims, err error) {
	var tokens *jwt.Token
	tokens, err = jwt.Parse(tokenSrt, func(*jwt.Token) (interface{}, error) {
		return []byte(SecretKey), nil
	})
	claims = tokens.Claims
	return claims, nil
}